package cn.rocksolid.sport.common.http;

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@ConfigurationProperties(prefix = "rocksolid.http.cors")
@ConditionalOnProperty(name = "rocksolid.http.cors.enable", havingValue = "true")
public class RockSolidHttpCorsConfig implements WebMvcConfigurer {

  private Long maxAge;

  private Boolean allowCredentials;

  private String[] allowedHeaders;

  private String[] allowedOriginPatterns;

  private String[] allowedMethods;

  @Override
  public void addCorsMappings(CorsRegistry registry) {
    CorsRegistration root = registry.addMapping("/**");
    root.maxAge(maxAge);
    root.allowCredentials(allowCredentials);
    root.allowedHeaders(allowedHeaders);
    //    root.allowedOrigins(allowedOrigins) // disabled for upgraded to great then springboot 2.4.0
    root.allowedOriginPatterns(allowedOriginPatterns);
    root.allowedMethods(allowedMethods);
  }

  public Long getMaxAge() {
    return maxAge;
  }

  public void setMaxAge(Long maxAge) {
    this.maxAge = maxAge;
  }

  public Boolean isAllowCredentials() {
    return allowCredentials;
  }

  public void setAllowCredentials(Boolean allowCredentials) {
    this.allowCredentials = allowCredentials;
  }

  public String[] getAllowedHeaders() {
    return allowedHeaders;
  }

  public void setAllowedHeaders(String[] allowedHeaders) {
    this.allowedHeaders = allowedHeaders;
  }

  public String[] getAllowedOriginPatterns() {
    return allowedOriginPatterns;
  }

  public void setAllowedOriginPatterns(String[] allowedOriginPatterns) {
    this.allowedOriginPatterns = allowedOriginPatterns;
  }

  public String[] getAllowedMethods() {
    return allowedMethods;
  }

  public void setAllowedMethods(String[] allowedMethods) {
    this.allowedMethods = allowedMethods;
  }
}